#!/usr/bin/env python

#    Copyright 2011,2012 Erik Persson
#
#    This file is part of the cell-sync-usrp project.
#
#    cell-sync-usrp is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    cell-sync-usrp is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with cell-sync-usrp.  If not, see <http://www.gnu.org/licenses/>.


##################################################
# Gnuradio Python Flow Graph
# Title: Top Block
# Generated: Wed Mar 30 09:06:37 2011
##################################################

from gnuradio import eng_notation
from gnuradio import gr
from gnuradio import uhd
from gnuradio.eng_option import eng_option
from gnuradio.gr import firdes
from grc_gnuradio import wxgui as grc_wxgui
from optparse import OptionParser
import wx
import time
import argparse



class top_block(grc_wxgui.top_block_gui):

    def __init__(self):
        grc_wxgui.top_block_gui.__init__(self, title="Top Block")

        ##################################################
        # Variables
        ##################################################
        self.samp_rate = samp_rate = 5.0e6
        self.freq = freq = 10700*200000

        ##################################################
        # Blocks
        ##################################################
        self.uhd_usrp_source_0 = uhd.usrp_source(
            device_addr="",
            io_type=uhd.io_type.COMPLEX_FLOAT32,
            num_channels=1,
        )
        self.uhd_usrp_source_0.set_samp_rate(samp_rate)
        self.uhd_usrp_source_0.set_center_freq(freq, 0)
        self.uhd_usrp_source_0.set_gain(1007, 0)
	#self.root_raised_cosine_filter_1 = gr.fir_filter_ccf(1, firdes.root_raised_cosine(1, samp_rate, samp_rate/2, 0.22, 30))
        #self.gr_rms_xx_0 = gr.rms_cf(1.0)#0.13)
        self.gr_probe_signal_f_0 = gr.probe_signal_f()
        self.gr_nlog10_ff_0 = gr.nlog10_ff(25, 1, 0)

	self.gr_nlog10_ff_0 = gr.nlog10_ff(1, 1, 0)
	self.gr_interp_fir_filter_xxx_0 = gr.interp_fir_filter_fff(1, ([1]))
	self.gr_fir_filter_xxx_0 = gr.fir_filter_fff(5, ([1,1,1,1,1] ))
	self.gr_complex_to_mag_squared_0 = gr.complex_to_mag_squared(1)

        ##################################################
        # Connections
        ##################################################
        #self.connect((self.uhd_usrp_source_0, 0), (self.root_raised_cosine_filter_1, 0))
        self.connect((self.gr_complex_to_mag_squared_0, 0), (self.gr_interp_fir_filter_xxx_0, 0))
	self.connect((self.gr_interp_fir_filter_xxx_0, 0), (self.gr_fir_filter_xxx_0, 0))
	self.connect((self.uhd_usrp_source_0, 0), (self.gr_complex_to_mag_squared_0, 0))
	self.connect((self.gr_fir_filter_xxx_0, 0), (self.gr_nlog10_ff_0, 0))
		
	#self.connect((self.root_raised_cosine_filter_1,0), (self.gr_rms_xx_0,0))
        #self.connect((self.gr_rms_xx_0, 0), (self.gr_nlog10_ff_0, 0))
        
	self.connect((self.gr_nlog10_ff_0, 0), (self.gr_probe_signal_f_0, 0))
	#self.connect((self.gr_rms_xx_0, 0), (self.gr_probe_signal_f_0, 0))

    def get_samp_rate(self):
        return self.samp_rate

    def set_samp_rate(self, samp_rate):
        self.samp_rate = samp_rate
        self.uhd_usrp_source_0.set_samp_rate(self.samp_rate)

    def get_freq(self):
        return self.freq

    def set_freq(self, freq):
        self.freq = freq
        self.uhd_usrp_source_0.set_center_freq(self.freq, 0)


def RSSIScan(UARFCNList):
    tb = top_block()
    tb.start()
    #tb.set_volume(10)
    tb.set_samp_rate(7.68e6)
    tb.set_freq(10700*200000);
    #time.sleep(1);
#    u = usrp_options.create_usrp_sink(options)
#    dac_rate = u.dac_rate()
#    rssi = self.u.read_aux_adc(0,0)
    #print tb.uhd_usrp_source_0.__class__.__dict__
    #dbi = tb.uhd_usrp_source_0.get_dboard_iface(0)
    #print dbi.__class__.__dict__
    #print "adc: ", dbi.read_aux_adc(uhd.uhd_swig.dboard_iface.UNIT_RX,uhd.uhd_swig.dboard_iface.AUX_ADC_A)
#    while (1==1):
#        v = dbi.read_aux_adc(uhd.uhd_swig.dboard_iface.UNIT_RX,uhd.uhd_swig.dboard_iface.AUX_ADC_B)
#        print "adc: ", v
#        #time.sleep(2)
#        if v <= 0.0:
#            break;

 
    sorted = []
    for freq in UARFCNList:
            tb.set_freq(freq*200000)
            time.sleep(0.1)	
            a=0
            value = 0.0
#            adc_v = 0.0
            result = []
            while (a<1):
                a=a+1
#                adc_v += dbi.read_aux_adc(uhd.uhd_swig.dboard_iface.UNIT_RX,uhd.uhd_swig.dboard_iface.AUX_ADC_A) / 1;
	        #v123 = tb.gr_probe_signal_f_0.level()
                #value += v123**2 / 100.0
                value += tb.gr_probe_signal_f_0.level() / 100
#                time.sleep(1)
#            print adc_v;
            i = 0
            while (i<len(sorted)):
                if (sorted[i][1] < value):#adc_v):
                    break
                i += 1
            sorted.insert(i,(freq,value))#adc_v))



    tb.stop()
    return sorted
                
      
    


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='WCDMA RSSI scan SDR application')
    parser.add_argument('UARFCN', nargs='+', type=int, default='0',
                        help='UARFCN (Freq = UARFCN*200000')
    parser.add_argument('--range', nargs="?", default='0', const='1', help='specify in order to perform RSSIScan on all UARFCNs from UARFCN[0] to UARFCN[1]')
    args = parser.parse_args()

    #args.UARFCN[0]*200000
    list = []
    if (args.UARFCN[0] == '0'):
	list = range(10630,10800)
    elif (args.range=='1'):
	if len(args.UARFCN) > 1:
            list = range(args.UARFCN[0],args.UARFCN[1]+1)
        else:
            list = [args.UARFCN[0]]
    else:
	list = args.UARFCN


    #result = RSSIScan([10789, 10638, 10639, 10787, 10635, 10700, 10630, 10642])
    #list = range(10630,10800)
    #list.append(10700)
    result = RSSIScan(list)



    print "RSSI result", result
    exit()
    
#    parser = OptionParser(option_class=eng_option, usage="%prog: [options]")
#    (options, args) = parser.parse_args()
#    tb = top_block()
#    
#    print "starting"
#    #tb.start()
#    tb.start()
#    #tb.set_volume(10)
#
#    start_freq =  2.1270e9 #2.1e9#10700*2.0e5#2112.5e6
#    end_freq = 2160e6#2170e6
#    freq_step = 2.0e5#5.0e6
#
#    tb.set_freq(start_freq)
#    tb.set_samp_rate(5.0e6)
#    
#    maxLevel = -1000000000.0
#   
#    maxFreq = 0.0
#    time.sleep(1)
#    freqList = [10638, 10787, 10635, 10700, 10630, 10642]
#    try:
#       
#        #while (tb.get_freq()<end_freq):
#        for freq in freqList:
#            tb.set_freq(freq*200000)
#            time.sleep(0.01)
#            a=0
#            value = 0.0
#            adc_v = 0.0
#            while (a<100):
#                a=a+1
#                adc_v += tb.uhd_usrp_source_0.read_aux_adc(0,0) / 100;
#                
#                #value += tb.gr_probe_signal_f_0.level() / 100.0
#                #value += tb.gr_probe_signal_f_0.level() / 100
#                time.sleep(0.01)
#                    
#            if (adc_v > maxLevel):#value > maxLevel):
#                maxFreq = tb.get_freq()
#                maxLevel = adc_v#value
#            
#            print "freq: ", tb.get_freq(), " = ", value
#            if (value > -95):
#                print "found channel: "
#                print (tb.get_freq())
#                print (adc_v)
#            
#            #tb.set_freq(tb.get_freq()+freq_step)
#            #time.sleep(0.01)
#        print "Scan completed"
#        print "freq, level"
#        print maxLevel
#        print maxFreq
#            
#    except(KeyboardInterrupt):
#        print "test"
#    
#    
#    tb.stop()
#    print "stopping"
    
    
        
        
